package com.yinxing.framework.convert;

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 字符串转为Date类型转换器
 */
public class StringToDateConvert implements Converter<String, Date> {

	private final static String shortPattern = "yyyy-MM-dd";
	private final static String middlePattern = "yyyy-MM-dd HH:mm";
	private final static String longPattern = "yyyy-MM-dd HH:mm:ss";
	
	@Override
	public Date convert(String source) {
		if(StringUtils.hasText(source)) {
			try {
				return autoMatch(source);
			} catch (ParseException e) {
				throw new IllegalArgumentException("this date argument's format must be " +
						"[yyyy-MM-dd , yyyy-MM-dd HH:mm , yyyy-MM-dd HH:mm:ss]");
			}
		}
		return null;
	}

	private Date autoMatch(String strDate) throws ParseException {
		String format = null;
		switch (strDate.length()) {
			case 10:
				format = shortPattern;
				break;
			case 16:
				format = middlePattern;
				break;
			case 19:
				format = longPattern;
				break;
		}
		return new SimpleDateFormat(format).parse(strDate);
	}
}
